﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button type="primary" icon="plus" v-if="hasPerm('bom_mainnode.Add')" @click="hanldleAdd('新建BOM')"
        >新建</a-button
      >
      <a-button
        type="primary"
        icon="edit"
        v-if="hasPerm('bom_mainnode.Edit')"
        @click="handleEdit(selectedKeys[0])"
        :disabled="!(selectedKeys.length > 0 && entity.Version)"
        >编辑</a-button
      >
      <a-button
        type="primary"
        icon="minus"
        v-if="hasPerm('bom_mainnode.Delete')"
        @click="handleDelete(selectedKeys[0])"
        :disabled="!hasTreeSelected()"
        >删除</a-button
      >
      <a-button type="primary" icon="redo" @click="redoData()">刷新</a-button>
      <div style="float: right; display: flex">
        <a-input v-model="queryParam.Keyword" placeholder="编号/名称/规格/成本项"></a-input>
        <a-button style="margin-right: 0" type="primary" @click="() => {this.pagination.current = 1; this.getDataList()}">查 询</a-button>
      </div>
    </div>
    <div class="treeTable">
      <div class="tree">
        <div style="display:flex">
          <a-input v-model="Keyword" placeholder="名称"></a-input>
          <a-button type="primary" @click="getFilterData()" icon="search"></a-button>
        </div>
        <a-tree
          v-if="treeShow"
          :load-data="onLoadData"
          :tree-data="treeData"
          @select="onSelect"
          :replaceFields="{ children: 'children', title: 'BomTreeName', key: 'Id' }"
        ></a-tree>
      </div>
      <div class="table">
        <div class="card">
          <a-row :gutter="20">
            <a-col :span="8"> <span>产品:</span> {{ entity.cInvName }}</a-col>
            <a-col :span="8"> <span>别名:</span> {{ entity.AliasName }}</a-col>
            <a-col :span="8"> <span>版本号:</span> {{ entity.Version }}</a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="8"> <span>版本说明:</span> {{ entity.VersionRemark }}</a-col>
            <a-col :span="8"> <span>更新日期:</span> {{ timeFormat(entity.CreateTime, 'YYYY-MM-DD') }}</a-col>
            <a-col :span="8"> <span>备注:</span> {{ entity.Remark }}</a-col>
          </a-row>
        </div>
        <a-table
          ref="table"
          :scroll="{ y: 560 }"
          :columns="columns"
          :rowKey="(row) => row.Id"
          :dataSource="data"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
          :bordered="true"
          size="small"
        >
          <!-- :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, columnWidth: '40px' }" -->
          <template slot="dataIndex" slot-scope="text, record, index">
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <template slot="CostType" slot-scope="text, record, index">
            {{ record.CostType == 0 ? '材料' : '成本项' }}
          </template>
        </a-table>
      </div>
    </div>

    <edit-form ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
const columns = [
  { title: '序号', dataIndex: 'Id', width: '50px', scopedSlots: { customRender: 'dataIndex' } },
  { title: '编号', dataIndex: 'SubCode' },
  { title: '名称', dataIndex: 'cInvName' },
  { title: '规格', dataIndex: 'cInvStd' },
  { title: '理论用量', dataIndex: 'Quantity', align: 'right' },
  { title: '成本项', dataIndex: 'CostName' },
  { title: '类型', dataIndex: 'CostType', scopedSlots: { customRender: 'CostType' } },
  { title: '备注', dataIndex: 'Remark' },
]

export default {
  components: {
    EditForm,
  },
  mounted() {
    this.getFilterData()
  },
  data() {
    return {
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], //设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
      },
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRowKeys: [],
      treeData: [],
      selectedKeys: [],
      treeShow: true,
      Keyword: '',
      entity: {},
    }
  },
  methods: {
    async redoData() {
      this.treeShow = false
      this.data = []
      this.entity = {}
      this.treeData = []
      this.selectedKeys = []
      await this.getFilterData()
      this.treeShow = true
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id, '编辑BOM')
    },
    onLoadData(treeNode) {
      let Id = treeNode.dataRef.Id
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        let data = []
        this.$http.post('/CostManagement/bom_mainnode/GetMainNodeDataList?parentId=' + Id, {}).then((res) => {
          if (res.Success) {
            data = res.Data
          }
          this.$set(treeNode.dataRef, 'children', data)
          // 懒加载时无法触发已打开节点  手动刷新触发
          // setTimeout(() => {
          //   this.expandedKeys.push(Id)
          //   this.expandedKeys.splice(this.expandedKeys.length - 1, 1)
          //   // console.log(this.expandedKeys, '节点懒加载')
          // }, 1)
          resolve()
        })
      })
    },
    // 树节点点击事件
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      if (selectedKeys.length <= 0) {
        this.data = []
        this.entity = {}
        this.pagination.current = 1
        this.pagination.total = 0
        return
      }
      this.getDataList()
      // 节点信息
      this.$http.post('/CostManagement/bom_mainnode/GetBomData?Id=' + this.selectedKeys[0]).then((res) => {
        console.log(res)
        if (res.Success) {
          this.entity = res.Data
        } else this.entity = {}
      })
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    async getFilterData() {
      this.treeShow = false
      await this.$http
        .post('/CostManagement/bom_mainnode/GetMainNodeDataList?BMainName=' + this.Keyword, {})
        .then((res) => {
          if (res.Success) {
            this.treeData = res.Data
            this.treeShow = true
          }
        })
    },
    getDataList() {
      this.selectedRowKeys = []
      this.loading = true
      this.queryParam.ParentId = this.selectedKeys[0]
      this.$http
        .post('/CostManagement/bom_subnode/GetSubNodeDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          // Search: { ParentId: this.selectedKeys[0] },
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          if (resJson.Total) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          } else {
            this.pagination.total = 0
          }
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasTreeSelected() {
      return this.selectedKeys.length > 0
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd(title) {
      this.$refs.editForm.openForm(null, title)
    },
    hanldleSubAdd(title) {
      if (this.selectedKeys.length <= 0) {
        return this.$message.error('请选择左侧产品信息')
      }
      const ParentId = this.selectedKeys[0]
      this.$refs.subEditForm.openForm(null, title, ParentId)
    },
    handleDelete(ids) {
      console.log(ids)
      this.$confirm({
        title: '确认删除吗?',
        onOk: () => {
          this.$http.post('/CostManagement/bom_mainnode/DeleteData', [ids]).then((resJson) => {
            if (resJson.Success) {
              this.$message.success('操作成功!')
              this.getFilterData()
              this.treeShow = true
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        },
      })
    },
    handleSubDelete(ids) {
      this.$confirm({
        title: '确认删除吗?',
        onOk: () => {
          this.$http.post('/CostManagement/bom_subnode/DeleteData', ids).then((resJson) => {
            if (resJson.Success) {
              this.$message.success('操作成功!')
              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        },
      })
    },
  },
}
</script>
<style scoped lang="less">
.treeTable {
  display: flex;
}
.tree {
  height: 600px;
  overflow-y: scroll;
  width: 270px;
  margin-right: 10px;
  border: 1px solid #e8e8e8;
  .filterList {
    cursor: pointer;
    margin: 5px 0;
    box-sizing: border-box;
    padding: 0 10px;
    span {
      padding: 3px 7px;
      border-radius: 3px;
    }
    .active {
      background-color: #bae7ff;
    }
  }
}
.table {
  flex: 1;
  .card {
    box-shadow: 1px 1px 5px #ccc;
    border-radius: 5px;
    margin-bottom: 10px;
    line-height: 2;
    box-sizing: border-box;
    padding: 5px 10px;
  }
}
</style>